import logging
import json
import yaml
import requests
from auto.apiSecurity.common.basic import process_input3, process_input4


def add_test_config(env, api_version_id, detail, test, openPath):
    if test == 1:
        with open('data/config/token.yml', 'r') as f:
            config = yaml.safe_load(f)
        with open('data/config/config.yaml', 'r') as f2:
            config_data = yaml.safe_load(f2)
        with open('data/config/project_id.txt', 'r') as f3:
            project_id = f3.read().strip()
        with open('data/config/api_id.txt', 'r') as f4:
            api_id = f4.read().strip()

        url = config_data['environments'][env]['host'] + config_data['environments'][env][
            'add_mock_open'] + api_id + "/versions/" + api_version_id + "/cases"
        token = config['token']
        headers = {'Content-Type': 'application/json', 'version': '2.0', 'Authorization': token, 'Tenantid': project_id}
        query_params = {
        }
        test_url = config_data['environments'][env]['accessUri'] + openPath
        # print(test_url)
        # print('提取出来的数据' + detail)

        data = process_input4(test_url, detail, api_id)
        # print('转换后的数据' + data)

        try:
            # 发送 打开 POST 请求
            response = requests.post(url, data=data, headers=headers, params=query_params)
            # 检查响应状态
            response.raise_for_status()  # 如果响应状态码不是 200，抛出异常
            parsed_data = response.json()
            logging.info("成功----接口有响应，响应数据：%s", json.dumps(parsed_data, ensure_ascii=False))
        except requests.exceptions.RequestException as e:
            logging.error("请求失败: %s", str(e))
        except json.JSONDecodeError:
            logging.error("解析 JSON 响应失败")
    else:
        logging.info("注意----该接口不配置test参数")
        pass
